package net.sureon.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sureon.biz.CompanyMgr;
import net.sureon.common.SureonConstants;
import net.sureon.common.exception.SureonException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * execute after home page
 * 
 * @author jason
 * 
 */
public class HomePageInterceptor extends HandlerInterceptorAdapter {
    private static final Log logger = LogFactory
        .getLog(HomePageInterceptor.class);
    CompanyMgr companyMgr;

    public boolean preHandle(HttpServletRequest request,
        HttpServletResponse response, Object handler) throws Exception {
        String siteUrl = extractSiteUrl(request.getRequestURL().toString());
        if(siteUrl != null){
            request.setAttribute(SureonConstants.REQ_ATTR_SITEURL, siteUrl);
            HttpSession sess = request.getSession(); 
            if(sess.getAttribute(SureonConstants.SESSION_ATTR_COMPAYCONFIG) == null){
            	try{
	            	long companyID = companyMgr.getCompany(siteUrl).getCompanyID();
	            	request.getSession().setAttribute(SureonConstants.SESSION_ATTR_COMPAYCONFIG,
	    				companyMgr.getCompanyConfig(
	    						companyID));
            	}catch(SureonException e){
            		logger.error("the inputed siteurl is not exist, " + siteUrl);
            	}
            }
        }
        return true;
    }

    public void postHandle(HttpServletRequest request,
        HttpServletResponse response, Object handler, ModelAndView modelAndView)
        throws Exception {

    }

    private static final String HTTPS = "https://";
    private static final String HTTP = "http://";
    private static final String WWW = "www";
    private static final String TITAON = "titaon";
    private static final char DOT = '.';
    private static final char SLASH = '/';

    private String extractSiteUrl(String requestURL) {
        String str = null;
        if(logger.isDebugEnabled()){
        	logger.debug("requestUrl: " + requestURL);
        }
        if (requestURL.startsWith(HTTPS)) {
            str = requestURL.substring(HTTPS.length());
        } else if (requestURL.startsWith(HTTP)) {
            str = requestURL.substring(HTTP.length());
        }
        if (str != null) {
        	int slashInd = str.indexOf(SLASH);
        	if(slashInd > 0){
        		str = str.substring(0, slashInd);
        	}
            int dotInd = str.indexOf(DOT);
            if (dotInd > 0) {
                String url = str.substring(0, dotInd);
                if (url.charAt(0) <= '9' && url.charAt(0) >= '0') {
                    logger
                        .error("not qualified(is not start with alpha) request url:"
                            + requestURL);
                    return null;
                }
                if(!WWW.equalsIgnoreCase(url) && !TITAON.equalsIgnoreCase(url)){
                	return url;
                }
            } else {
                logger.error("not qualified(cannot find dot) request url:"
                    + requestURL);
            }
        } else {
            logger.error("not qualified(didn't find http://) request url:"
                + requestURL);
        }
        return null;
    }

	public CompanyMgr getCompanyMgr() {
		return companyMgr;
	}

	public void setCompanyMgr(CompanyMgr companyMgr) {
		this.companyMgr = companyMgr;
	}
}